package com.distributedDataBase.service;

import com.distributedDataBase.mapper.UserMapper;
import com.distributedDataBase.pojo.PageMyInfo;
import com.distributedDataBase.pojo.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    //业务逻辑层service调用mapper层
    @Autowired
    private UserMapper userMapper;


    @Override
    public PageMyInfo<User> page(String username, Integer pageNow, Integer pageSize) {

        //封装分页相关数据的一个对象
        PageMyInfo<User> pageInfo = new PageMyInfo<>();

        //封装当前页
        pageInfo.setPageNow(pageNow);
        //封装每页显示的条数
        pageInfo.setPageSize(pageSize);
        //封装总的条数
        Integer rows = userMapper.countUsers(username);
        pageInfo.setRows(rows);

        //封装总的页数
        Integer pageTotal = rows / pageSize;

        if(rows % pageSize !=0)
            pageTotal++;

        pageInfo.setPageTotal(pageTotal);

        //条件查询 + 分页 => 查询的数据
        //封装此次查询的数据
        List<User> userList = userMapper.listUsers(username,pageNow,pageSize);
        pageInfo.setData(userList);

        return pageInfo;
    }

    @Override
    public PageInfo<User> pageUsers(String username, Integer pageNow, Integer pageSize) {
        //分页底层 - 动态代理 + 拦截器技术
        //必须要先设置分页的相关参数
        PageHelper.startPage(pageNow,pageSize);

        //调用根据条件查询的用户集合
        List<User> userList = userMapper.listByUsername(username);

        //定义内置的分页的对象
        PageInfo<User> pageInfo = new PageInfo<>(userList);

        return pageInfo;
    }

    @Override
    public User searchUserByEmail(String email) {
        User user = userMapper.findUserByEmail(email);
        return user;
    }
}
